package com.itheima.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.pojo.User;
import com.itheima.service.UserSevice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserSevice userSevice;

	//分页查询用户
    @GetMapping("/{currentPage}/{pageSize}")
    public Result selectByPage(@PathVariable  int currentPage,@PathVariable int pageSize) throws IOException {

        IPage<User> page = new Page<>(currentPage,pageSize);
        userSevice.page(page);

        Result result = new Result();
        Map map = new HashMap<>();
        map.put("rows",page.getRecords());
        map.put("totalCount",page.getTotal());
        result.setData(map);
        return result;
    }
    /**
     * 保存用户
     * @param user 用户数据
     */
    @PostMapping
    public Result add(@RequestBody  User user) {
        userSevice.save(user);
        Result result = new Result();
        result.setCode(Code.SAVE_OK);
        return result;
    }

    /**
     * 根据用户id查询用户
     * @param id 用户id
     */
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        boolean b = userSevice.removeById(id);
        Result result = new Result();
        result.setCode(Code.DELETE_OK);
        return result;
    }

    /**
     * 更新用户
     * @param user 用户数据
     */
    @PutMapping
    public Result update(@RequestBody User user) {
        userSevice.updateById(user);
        Result result = new Result();
        result.setCode(Code.UPDATE_OK);
        return result;
    }

}
